﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Events;
using Autodesk.Revit.UI;
using YArchitech.LIB;
using YJKView;

namespace YJKDimensionModel.LevelDimension
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdLevelDimension : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			if (2015 >= Convert.ToInt32(cmdData.Application.Application.VersionNumber))
			{
				MessageBox.Show("此功能只在Revit2016及其以上版本可用", "盈建科提示");
				return Autodesk.Revit.UI.Result.Succeeded;
			}
			CmdViewType types = (CmdViewType)43;
			if (SwitchView.SetUsableView(types, cmdData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Succeeded;
			}
			Process currentProcess = Process.GetCurrentProcess();
			IntPtr mainWindowHandle = currentProcess.MainWindowHandle;
			cmdData.Application.Application.FailuresProcessing += this.OnFailuresProcessing;
			YJKWindowHandle owner = new YJKWindowHandle(mainWindowHandle);
			LevelDimensionForm levelDimensionForm = new LevelDimensionForm(mainWindowHandle, cmdData);
			levelDimensionForm.Show(owner);
			LevelDimensionManager levelDimensionManager = new LevelDimensionManager(cmdData);
			try
			{
				if (!levelDimensionManager.ViewValidating())
				{
					return Autodesk.Revit.UI.Result.Failed;
				}
				levelDimensionManager.DrawLevelDimension(levelDimensionForm);
				levelDimensionForm.Close();
			}
			catch (Exception)
			{
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private void OnFailuresProcessing(object sender, FailuresProcessingEventArgs e)
		{
			FailuresAccessor failuresAccessor = e.GetFailuresAccessor();
			string transactionName = failuresAccessor.GetTransactionName();
			IList<FailureMessageAccessor> failureMessages = failuresAccessor.GetFailureMessages();
			if (failureMessages.Count == 0)
			{
				e.SetProcessingResult((FailureProcessingResult)0);
				return;
			}
			if (transactionName.Equals("Create DetailCurve") || transactionName.Equals("Craete Group") || transactionName.Equals("Create Text"))
			{
				foreach (FailureMessageAccessor failureMessageAccessor in failureMessages)
				{
					failuresAccessor.DeleteWarning(failureMessageAccessor);
				}
				e.SetProcessingResult((FailureProcessingResult)1);
				return;
			}
			e.SetProcessingResult((FailureProcessingResult)0);
		}
	}
}
